package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.config.properties.WechatMiniPayProperties;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.aliyun.AliOSSUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.dao.UserInfoDao;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.util.Base64;
import java.util.List;

@Api(tags = {"文件上传"})
@RestController
@RequestMapping("/img")
public class UploadFileController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadFileController.class);

    @Resource
    private WechatMiniPayProperties wechatMiniPayProperties;

    @Resource
    private UserInfoDao userInfoDao;

    /**
     * 根据用户id上传头像
     *
     * @param file
     * @param
     * @return
     */
    @ApiOperation(value = "单文件上传", notes = "单文件上传", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件对象", required = true, paramType = "form", dataType = "_file")
    })
    @PostMapping("/userUploadImg")
    public WebResponse addUserImg(@RequestParam(value = "file") MultipartFile file) {
        String URL = AliOSSUtil.uploadFile(file, "userInfo");
        LOGGER.info("文件的访问地址===>" + URL);
        return WebResponse.successData(URL);
    }

    /**
     * 批量OSS上传
     *
     * @param files
     * @return
     */
    @ApiOperation(value = "批量上传", notes = "批量上传", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件对象数组", required = true, paramType = "form", dataType = "_file")
    })
    @PostMapping("/batchUploadImg")
    public WebResponse batchUploadImg(@RequestParam(value = "file") List<MultipartFile> files) {
        List<String> URL = AliOSSUtil.batchUploadImg(files, "laundry");
        LOGGER.info("文件的访问地址===>" + URL);
        return WebResponse.successData(URL);
    }

    /**
     * 生成太阳码（appUserId、userType、page、env_version）
     *
     * @param data
     * @return
     * @throws Exception
     */
    @PostMapping("/getSunImg")
    public WebResponse addOrderListDetails(@RequestBody String data) throws Exception {
        JSONObject jsonObject1 = JSON.parseObject(data);
        String appUserId = jsonObject1.getString("appUserId"); //邀请人id
        String userType = jsonObject1.getString("userType"); //邀请人类型 用户1 ，骑手2
        String page = jsonObject1.getString("page"); //去用户小程序端首页(pages/clothes/index) 去骑手端首页(pages/mytask/index)
        String envVersion = jsonObject1.getString("env_version"); //正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版

        if (JSBUtil.isEmptyString(page) || JSBUtil.isEmptyString(userType) || JSBUtil.isEmptyString(appUserId) || JSBUtil.isEmptyString(envVersion)) {
            return WebResponse.failOfParameter();
        }

        //根据appUserId查询对应的主键id （登录后配合userType（t） 反向查询出id）
        String id = "";
        if ("2".equals(userType)) { // 骑手2
            id = userInfoDao.getRiderInfo(appUserId);
        } else { //用户1
            id =  userInfoDao.getUserInfoId(appUserId);
        }


        /**
         * 获取access_token
         */
        String accessTokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", wechatMiniPayProperties.getAppId(), wechatMiniPayProperties.getAppSecret());
        String s = HttpUtil.sendGet(accessTokenUrl, null, null, null);
        JSONObject jsonObject2 = JSONObject.parseObject(s);
        String access_tokens = jsonObject2.getString("access_token");
        String url = String.format("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", access_tokens);

        CloseableHttpClient client11 = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);

        JSONObject jsonb = new JSONObject();
        jsonb.put("scene", String.format("a=%s&t=%s", id, userType)); // a:邀请人主键id , t: 用户0 ，骑手1
        jsonb.put("page", page); //跳转页面
        jsonb.put("env_version", envVersion); //跳转对应版本

        StringEntity postingString = new StringEntity(jsonb.toString(), "UTF-8");
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = client11.execute(post);

//        InputStream content = response.getEntity().getContent();
//        byte[] read = read(content);
        HttpEntity entity = response.getEntity();
        byte[] byteArray = EntityUtils.toByteArray(entity);

        // 若成功将bytes转成base64并返回给前端
        String base64String = Base64.getEncoder().encodeToString(byteArray);// 转码
        MultipartFile multipartFile = base64ToMultipartFile(base64String);
        String path = AliOSSUtil.uploadFile(multipartFile, "userInfo");
        return WebResponse.successData(path);
    }

    public static byte[] read(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * base64Data转 MultipartFile上传阿里云
     *
     * @param base64String
     * @return
     * @throws IOException
     */
    public static MultipartFile base64ToMultipartFile(String base64String) throws IOException {
        byte[] content = org.apache.commons.codec.binary.Base64.decodeBase64(base64String);
        MockMultipartFile mockMultipartFile = new MockMultipartFile(
                "file", "wechatSunImgCodeBase64Str.png", ContentType.APPLICATION_OCTET_STREAM.toString(), content);
        return mockMultipartFile;
    }


//    public static MultipartFile base64ToMultipartFile(String base64Data) throws IOException {
//        // 解码 Base64 数据为字节数组
//        byte[] decodedBytes = Base64.getDecoder().decode(base64Data);
//
//        // 创建临时文件并写入解码后的数据
//        File tempFile = File.createTempFile("jsb-temp", null);
//        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
//            fos.write(decodedBytes);
//        }
//
//        // 将临时文件转换为 MultipartFile
//        Path tempFilePath = tempFile.toPath();
//        String originalFilename = tempFile.getName();
//        String contentType = Files.probeContentType(tempFilePath);
//        byte[] fileContent = Files.readAllBytes(tempFilePath);
//        MultipartFile multipartFile = new MockMultipartFile(
//                originalFilename,
//                originalFilename,
//                contentType,
//                fileContent
//        );
//
//        // 删除临时文件
//        Files.deleteIfExists(tempFilePath);
//
//        return multipartFile;
//    }


}
